import pygame

WIDTH = 800
HEIGHT = 800

PADDING = 40
GRID_WIDTH = (WIDTH - 40 * 2) // 3
GRID_HEIGHT = (HEIGHT - 40 * 2) // 3

GREY = (192, 192, 192)
BLACK = (0, 0, 0)
BLUE = (32, 32, 224)

# 棋盘状态
class ChessBoard(object):
    def __init__(self):
        self.state = ["1", "0", "3", "4", "5", "6", "7", "8", "2"]
        self.pos = self.state.index("0")

    def move_right(self):
        if (self.pos % 3 == 0):
            return

        tpos = self.pos - 1
        self.state[self.pos] = self.state[tpos]
        self.state[tpos] = "0"

        self.pos = tpos

        draw()
        
    def move_left(self):
        if (self.pos % 3 == 2):
            return

        tpos = self.pos + 1
        self.state[self.pos] = self.state[tpos]
        self.state[tpos] = "0"

        self.pos = tpos

        draw()
        
    def move_up(self):
        if (self.pos // 3 == 2):
            return

        tpos = self.pos + 3
        self.state[self.pos] = self.state[tpos]
        self.state[tpos] = "0"

        self.pos = tpos

        draw()
        
    def move_down(self):
        if (self.pos // 3 == 0):
            return

        tpos = self.pos - 3
        self.state[self.pos] = self.state[tpos]
        self.state[tpos] = "0"

        self.pos = tpos

        draw()
        

pygame.init()

# 创建屏幕
screen = pygame.display.set_mode((WIDTH, HEIGHT))

# 创建棋盘
board = ChessBoard()

def draw_text(font, msg, row, line):
    text = font.render(msg, True, BLUE)
    x, y = font.size(msg)
    screen.blit(text, 
        (PADDING + GRID_WIDTH // 2 - x // 2 + line * GRID_WIDTH, 
         PADDING + GRID_HEIGHT // 2 - y // 2 + row * GRID_HEIGHT))

def draw():
    screen.fill(GREY)
    for i in range(4):
        pygame.draw.line(screen, BLACK, 
            (PADDING, PADDING + i * GRID_HEIGHT), 
            (WIDTH - PADDING, PADDING + i * GRID_HEIGHT), 2)

    for i in range(4):
        pygame.draw.line(screen, BLACK, 
            (PADDING + i * GRID_WIDTH, PADDING),
            (PADDING + i * GRID_WIDTH, WIDTH - PADDING), 2)

    font = pygame.font.SysFont("arial", 200)
    
    for i in range(9):
        t = board.state[i]
        if (t == "0"):
            continue

        draw_text(font, t, i // 3, i % 3)

    pygame.display.update()

draw()

going = True

while going:
    for evt in pygame.event.get():
        if evt.type == pygame.QUIT:
            going = False
        elif evt.type == pygame.KEYDOWN:
            if evt.key == pygame.K_RIGHT:
                board.move_right()
            elif evt.key == pygame.K_LEFT:
                board.move_left()
            elif evt.key == pygame.K_UP:
                board.move_up()
            elif evt.key == pygame.K_DOWN:
                board.move_down()
